# _*_ coding:utf-8 _*_
# @Time  : 2023.09.07
# @Author: zizlee
import json
import pathlib
from typing import List
from fastapi import APIRouter, Body, Depends
from pydantic import BaseModel
from db_utils import BaseDatabaseConnection
from utils.jwt_token import QuietTokenPayload
from response import APIResponse
from settings import STATIC_HOST, FILE_STORAGE


class SuggestItem(BaseModel):
    image_list: List[str]
    text: str


class SuggestApi:
    def create_suggest(self, payload: QuietTokenPayload, suggest: SuggestItem):
        if len(suggest.image_list) < 1 and len(suggest.text.strip()) < 1:
            return APIResponse.validate_error(detail='请填写内容再保存')
        image_list = []
        for img in suggest.image_list:
            img_sql = img.replace(STATIC_HOST, '')
            img_file = pathlib.Path(FILE_STORAGE).joinpath(img_sql)
            if img_file.exists() and img_file.is_file():
                image_list.append(img_sql)
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute("INSERT INTO ruizhi_suggest(user_id,suggest,image_list) VALUES (%s,%s,%s);",
                                [payload.user_id(), suggest.text, json.dumps(image_list)])
        return APIResponse.success(msg='非常感谢！我们已收到您的反馈。')


suggest_router = APIRouter()


@suggest_router.post('/')  # 上传建议
def create_suggest(payload: QuietTokenPayload = Depends(QuietTokenPayload), suggest: SuggestItem = Body(...)):
    return SuggestApi().create_suggest(payload=payload, suggest=suggest)
